Opening a file and saving data to a file I would like to check to see if the file exists to prevent segmentation fault when trying to open a file that isn't there.
When saving a file I would like to know if it already exists and give the user the opportunity to rename the file being saved or overwrite the existying file.
Here is what I have written and it works as long as everything is perfect but it closes the program with an error fault if the file I am trying to open doesn't exist. When saving the file it has no safe guard if the file exists and it just overwrites it.
Code:
// openfile begins ****************************************************
int openfile(void)
{
FILE *fptr;
char *filename ="filename";
char filespec[79];
input(filename,79); // get path and filename from input()
strcpy(filespec, lin);
lin[0] = '\0';
clearscreen();
printf("\t\n\n Reading copy of %s from disk\n\n\n", filespec);
fptr = fopen(filespec, "r"); // can I use an "if" statement to test ??
// would a while loop work so I can loop back to the beginning of the function ??
fread(&all, sizeof(all), 1, fptr);
fclose(fptr);
return(chois);
// add if statement for no file access warning and retry
}
// openfile ends ******************************************************
// savfil begins ******************************************************
int savfil(void)
{
FILE *fptr;
char *filename = "filename";
char filespec[79];
input(filename, 79);
strcpy(filespec, lin);
lin[0] = '\0';
clearscreen();
printf("\t\n\n Writing copy of %s to disk\n\n\n", filespec);
fptr = fopen(filespec, "w");
fwrite(&all, sizeof(all), 1, fptr);
fclose(fptr);
return 0;
// add if statement to warn if file exists ??
// add rename current file or overwrite ??
}
// savfil ends ********************************************************
I am coding in ANSI C99, using Geany on a I5 quad core 2.67 GHz and 6 Gb of ram.
Thanks for any help for this old man.